﻿#include "All-profilePage.h"
#include "All-merchantRegister.h"
#include "All-riderRegister.h"
#include <QFileDialog>

ProfilePage::ProfilePage(database &db, QWidget *parent)
    : QWidget(parent), db(db)
{
    setupUI();
}

ProfilePage::~ProfilePage()
{
}

void ProfilePage::setupUI()
{
    // 创建主布局
    QVBoxLayout *mainLayout = new QVBoxLayout(this);
    mainLayout->setSpacing(15);
    mainLayout->setContentsMargins(20, 20, 20, 20);

    // 创建标题
    QLabel *titleLabel = new QLabel("个人信息", this);
    titleLabel->setStyleSheet("font-size: 20pt; font-weight: bold; margin-bottom: 20px;");
    titleLabel->setAlignment(Qt::AlignCenter);
    mainLayout->addWidget(titleLabel);

    // 创建表单容器
    QWidget *formContainer = new QWidget(this);
    formContainer->setStyleSheet("background-color: #f5f5f5; border-radius: 8px; padding: 20px;");
    QVBoxLayout *containerLayout = new QVBoxLayout(formContainer);
    
    // 创建表单布局
    QFormLayout *formLayout = new QFormLayout();
    formLayout->setSpacing(20);
    formLayout->setFieldGrowthPolicy(QFormLayout::AllNonFixedFieldsGrow);
    formLayout->setLabelAlignment(Qt::AlignRight | Qt::AlignVCenter);

    // 样式
    QString labelStyle = "font-size: 14pt; font-weight: bold; color: #333;";
    QString valueStyle = "font-size: 14pt; color: #555; padding: 8px;";
    QString lineEditStyle = "font-size: 14pt; padding: 8px; border: 1px solid #ccc; border-radius: 4px; background-color: white;";

    // 用户ID显示
    QLabel *userIdTitleLabel = new QLabel("用户ID:", this);
    userIdTitleLabel->setStyleSheet(labelStyle);
    userIdLabel = new QLabel(this);
    userIdLabel->setStyleSheet(valueStyle);
    formLayout->addRow(userIdTitleLabel, userIdLabel);

    // 用户身份显示
    QLabel *identityTitleLabel = new QLabel("用户身份:", this);
    identityTitleLabel->setStyleSheet(labelStyle);
    identityLabel = new QLabel(this);
    identityLabel->setStyleSheet(valueStyle);
    formLayout->addRow(identityTitleLabel, identityLabel);

    // 用户昵称编辑
    QLabel *nameTitleLabel = new QLabel("昵称:", this);
    nameTitleLabel->setStyleSheet(labelStyle);
    
    QWidget *nameWidget = new QWidget(this);
    QHBoxLayout *nameLayout = new QHBoxLayout(nameWidget);
    nameLayout->setContentsMargins(0, 0, 0, 0);
    nameLayout->setSpacing(10);
    
    nameEdit = new QLineEdit(this);
    nameEdit->setStyleSheet(lineEditStyle);
    nameEdit->setReadOnly(true);  // 初始状态不可编辑
    
    nameEditCheckBox = new QCheckBox("编辑", this);
    nameEditCheckBox->setStyleSheet("font-size: 12pt;");
    connect(nameEditCheckBox, &QCheckBox::toggled, this, &ProfilePage::onNameEditToggled);
    
    saveNameButton = new QPushButton("保存", this);
    saveNameButton->setStyleSheet("font-size: 12pt; padding: 6px 12px; border-radius: 4px; background-color: #4CAF50; color: white;");
    saveNameButton->setEnabled(false);  // 初始状态不可点击
    connect(saveNameButton, &QPushButton::clicked, this, &ProfilePage::onSaveNameClicked);
    
    nameLayout->addWidget(nameEdit, 1);
    nameLayout->addWidget(nameEditCheckBox);
    nameLayout->addWidget(saveNameButton);
    
    formLayout->addRow(nameTitleLabel, nameWidget);

    // 用户地址编辑
    QLabel *addressTitleLabel = new QLabel("地址:", this);
    addressTitleLabel->setStyleSheet(labelStyle);
    
    QWidget *addressWidget = new QWidget(this);
    QHBoxLayout *addressLayout = new QHBoxLayout(addressWidget);
    addressLayout->setContentsMargins(0, 0, 0, 0);
    addressLayout->setSpacing(10);
    
    addressEdit = new QLineEdit(this);
    addressEdit->setStyleSheet(lineEditStyle);
    addressEdit->setReadOnly(true);  // 初始状态不可编辑
    
    addressEditCheckBox = new QCheckBox("编辑", this);
    addressEditCheckBox->setStyleSheet("font-size: 12pt;");
    connect(addressEditCheckBox, &QCheckBox::toggled, this, &ProfilePage::onAddressEditToggled);
    
    saveAddressButton = new QPushButton("保存", this);
    saveAddressButton->setStyleSheet("font-size: 12pt; padding: 6px 12px; border-radius: 4px; background-color: #4CAF50; color: white;");
    saveAddressButton->setEnabled(false);  // 初始状态不可点击
    connect(saveAddressButton, &QPushButton::clicked, this, &ProfilePage::onSaveAddressClicked);
    
    addressLayout->addWidget(addressEdit, 1);
    addressLayout->addWidget(addressEditCheckBox);
    addressLayout->addWidget(saveAddressButton);
    
    formLayout->addRow(addressTitleLabel, addressWidget);
    
    // 钱包余额和充值按钮（仅普通用户显示）
    QLabel *walletTitleLabel = new QLabel("钱包:", this);
    walletTitleLabel->setStyleSheet(labelStyle);
    
    QWidget *walletWidget = new QWidget(this);
    QHBoxLayout *walletLayout = new QHBoxLayout(walletWidget);
    walletLayout->setContentsMargins(0, 0, 0, 0);
    walletLayout->setSpacing(10);
    
    walletLabel = new QLabel("0.00 元", this);
    walletLabel->setStyleSheet(valueStyle + "background-color: #f9f9f9; border: 1px solid #ddd; border-radius: 4px;");
    
    rechargeButton = new QPushButton("充值", this);
    rechargeButton->setStyleSheet("font-size: 12pt; padding: 6px 12px; border-radius: 4px; background-color: #FF9800; color: white;");
    connect(rechargeButton, &QPushButton::clicked, this, &ProfilePage::onRechargeClicked);
    
    walletLayout->addWidget(walletLabel, 1);
    walletLayout->addWidget(rechargeButton);
    
    formLayout->addRow(walletTitleLabel, walletWidget);
    
    // 商家头像和营业状态（仅商家显示）
    avatarLabel = new QLabel(this);
    avatarLabel->setFixedSize(100, 100);
    avatarLabel->setAlignment(Qt::AlignCenter);
    avatarLabel->setStyleSheet("border: 2px dashed #aaa; border-radius: 50px; background-color: #f9f9f9;");
    avatarLabel->installEventFilter(this); // 安装事件过滤器
    avatarLabel->setText("<a href='change'>点击更换头像</a>");
    avatarLabel->setOpenExternalLinks(false);
    connect(avatarLabel, &QLabel::linkActivated, this, &ProfilePage::onChangeAvatarClicked);
    changeAvatarButton = new QPushButton("更换头像", this);
    connect(changeAvatarButton, &QPushButton::clicked, this, &ProfilePage::onChangeAvatarClicked);
    statusLabel = new QLabel(this);
    statusLabel->setStyleSheet("font-size: 14pt; color: #555; padding: 8px;");
    toggleStatusButton = new QPushButton("切换营业状态", this);
    connect(toggleStatusButton, &QPushButton::clicked, this, &ProfilePage::onStatusToggleClicked);
    
    // 在商家身份时插入头像和营业状态控件
    if (userIdentity == 2) {
        QHBoxLayout *avatarLayout = new QHBoxLayout();
        avatarLayout->addWidget(avatarLabel);
        avatarLayout->addWidget(changeAvatarButton);
        formLayout->insertRow(0, new QLabel("商家头像:", this), avatarLayout);
        QHBoxLayout *statusLayout = new QHBoxLayout();
        statusLayout->addWidget(statusLabel);
        statusLayout->addWidget(toggleStatusButton);
        formLayout->insertRow(1, new QLabel("营业状态:", this), statusLayout);
    }
    
    containerLayout->addLayout(formLayout);
    mainLayout->addWidget(formContainer, 1);

    // 添加修改密码按钮
    changePasswordButton = new QPushButton("修改密码", this);
    changePasswordButton->setStyleSheet("font-size: 14pt; padding: 10px 20px; border-radius: 4px; background-color: #2196F3; color: white; margin-top: 20px;");
    connect(changePasswordButton, &QPushButton::clicked, this, &ProfilePage::onChangePasswordClicked);
    
    // 添加身份转换按钮
    becomeMerchantButton = new QPushButton("成为商户", this);
    becomeMerchantButton->setStyleSheet("font-size: 14pt; padding: 10px 20px; border-radius: 4px; background-color: #FF9800; color: white; margin-top: 10px;");
    connect(becomeMerchantButton, &QPushButton::clicked, this, &ProfilePage::onBecomeMerchantClicked);
    
    becomeRiderButton = new QPushButton("加入骑手", this);
    becomeRiderButton->setStyleSheet("font-size: 14pt; padding: 10px 20px; border-radius: 4px; background-color: #9C27B0; color: white; margin-top: 10px;");
    connect(becomeRiderButton, &QPushButton::clicked, this, &ProfilePage::onBecomeRiderClicked);
    
    QHBoxLayout *buttonLayout = new QHBoxLayout();
    buttonLayout->addStretch();
    buttonLayout->addWidget(changePasswordButton);
    buttonLayout->addWidget(becomeMerchantButton);
    buttonLayout->addWidget(becomeRiderButton);
    buttonLayout->addStretch();
    
    mainLayout->addLayout(buttonLayout);
    mainLayout->addStretch();
}

void ProfilePage::setUserInfo(int userIdentity, int phoneId, const QString &username)
{
    this->userIdentity = userIdentity;
    this->phoneId = phoneId;
    this->username = username;
    
    // 根据用户身份设置身份名称
    switch(userIdentity) {
    case 0:
        identityName = "管理员";
        break;
    case 1:
        identityName = "普通用户";
        break;
    case 2:
        identityName = "商户";
        break;
    case 3:
        identityName = "骑手";
        break;
    default:
        identityName = "未知身份";
        break;
    }
    
    // 加载用户信息
    loadUserInfo();
}

void ProfilePage::loadUserInfo()
{
    // 如果未设置用户信息，则不加载
    if (phoneId < 0) {
        return;
    }
    // --- 修正：每次加载前重置地址控件 ---
    addressEdit->setText("");
    addressEdit->setEnabled(true);
    addressEdit->setReadOnly(true);
    addressEditCheckBox->setChecked(false);
    addressEditCheckBox->setEnabled(true);
    saveAddressButton->setEnabled(false);
    originalAddress = "";
    address = "";
    // --- 结束修正 ---
    // 显示基本信息
    userIdLabel->setText(QString::number(phoneId));
    identityLabel->setText(identityName);
    nameEdit->setText(username);
    originalName = username;
    
    // 普通用户和商户需要显示地址
    if (userIdentity == 1 || userIdentity == 2) {
        // 查询地址ID
        QString sql;
        QString sql2;
        if(userIdentity == 1){
            sql = QString("SELECT user_id FROM user WHERE phone_id = %1").arg(phoneId);
        }else{
            sql = QString("SELECT address_id FROM business WHERE phone_id = %1").arg(phoneId);
        }
        qDebug()<<"profilePage-189:"<<sql;
        QSqlQuery query = db.exec(sql);
        if (query.next()) {
            userId = query.value(0).toInt();
            // 查询地址
            if(userIdentity == 1){
                sql2 = QString("SELECT address FROM address WHERE user_id = %1 and address_status = 1").arg(userId);
            }else{
                sql2 = QString("SELECT address FROM address WHERE address_id = %1 ").arg(userId);
            }
            qDebug()<<"profilePage-196:"<<sql2;
            query = db.exec(sql2,"225-个人信息页的地址");
            if (query.next()) {
                address = query.value(0).toString();
                addressEdit->setText(address);
                originalAddress = address;
            }else{
                qDebug()<<"225行query.next()失败";
                // 没有地址，清空内容
                addressEdit->setText("");
                originalAddress = "";
                address = "";
            }
        }else{
            qDebug()<<"220行query.next()失败";
        }
    } else {
        // 其他用户类型不显示地址
        addressEdit->setText("不适用");
        addressEdit->setEnabled(false);
        addressEditCheckBox->setEnabled(false);
        saveAddressButton->setEnabled(false);
        originalAddress = "";
        address = "";
    }
    
    // 控制钱包显示和充值按钮
    walletLabel->parentWidget()->setVisible(true); // 所有用户都显示钱包区域
    
    // 根据用户身份获取并显示钱包余额
    QString sql;
    switch(userIdentity) {
    case 1: // 普通用户
        sql = QString("SELECT user_money FROM user WHERE phone_id = %1").arg(phoneId);
        rechargeButton->setVisible(true); // 普通用户显示充值按钮
        break;
    case 2: // 商户
        sql = QString("SELECT income FROM business WHERE phone_id = %1").arg(phoneId);
        rechargeButton->setVisible(false); // 商户不显示充值按钮
        break;
    case 3: // 骑手
        sql = QString("SELECT Income FROM rider WHERE phone_id = %1").arg(phoneId);
        rechargeButton->setVisible(false); // 骑手不显示充值按钮
        break;
    default: // 管理员或其他身份
        walletLabel->parentWidget()->setVisible(false); // 其他用户不显示钱包区域
        break;
    }
    
    // 查询钱包余额
    if (userIdentity == 1 || userIdentity == 2 || userIdentity == 3) {
        QSqlQuery query = db.exec(sql);
        if (query.next()) {
            walletBalance = query.value(0).toDouble();
            updateWalletDisplay();
        }
    }
    
    // 控制身份转换按钮的可见性
    bool isUser = (userIdentity == 1); // 仅普通用户显示身份转换按钮
    becomeMerchantButton->setVisible(isUser);
    becomeRiderButton->setVisible(isUser);
    
    // 根据用户身份控制身份转换按钮的可用性
    // 只有普通用户(1)可以申请成为商户或骑手
    bool canChangeIdentity = (userIdentity == 1);
    becomeMerchantButton->setEnabled(canChangeIdentity);
    becomeRiderButton->setEnabled(canChangeIdentity);
    
    // 设置按钮提示信息
    if (!canChangeIdentity) {
        becomeMerchantButton->setToolTip("您当前身份不能申请成为商户");
        becomeRiderButton->setToolTip("您当前身份不能申请成为骑手");
    } else {
        becomeMerchantButton->setToolTip("点击申请成为商户");
        becomeRiderButton->setToolTip("点击申请成为骑手");
    }

    // 商家头像和营业状态（仅商家）
    if (userIdentity == 2) {
        // 查询头像和营业状态
        QString sql = QString("SELECT img, status FROM business WHERE phone_id = %1").arg(phoneId);
        QSqlQuery query = db.exec(sql);
        if (query.next()) {
            avatarPath = query.value(0).toString();
            businessStatus = query.value(1).toInt();
        } else {
            avatarPath = "";
            businessStatus = 1;
        }
        // 显示头像，若无则用默认
        QString defaultAvatar = ":/img/img/clm.png";
        QString showPath = (!avatarPath.isEmpty() && QFile::exists(avatarPath)) ? avatarPath : defaultAvatar;
        QPixmap pixmap(showPath);
        if (!pixmap.isNull()) {
            pixmap = pixmap.scaled(avatarLabel->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation);
            avatarLabel->setPixmap(pixmap);
        } else {
            avatarLabel->setText("<a href='change'>点击更换头像</a>");
        }
        // 显示营业状态
        statusLabel->setText(businessStatus == 1 ? "营业中" : "休息中");
        toggleStatusButton->setText(businessStatus == 1 ? "设为休息" : "设为营业");
        avatarLabel->setVisible(true);
        changeAvatarButton->setVisible(true);
        statusLabel->setVisible(true);
        toggleStatusButton->setVisible(true);
    } else {
        if (avatarLabel) avatarLabel->setVisible(false);
        if (changeAvatarButton) changeAvatarButton->setVisible(false);
        if (statusLabel) statusLabel->setVisible(false);
        if (toggleStatusButton) toggleStatusButton->setVisible(false);
    }
}

void ProfilePage::updateWalletDisplay()
{
    // 根据用户身份设置不同的钱包显示文本
    QString walletText;
    switch(userIdentity) {
    case 1: // 普通用户
        walletText = QString("%1 元").arg(walletBalance, 0, 'f', 2);
        break;
    case 2: // 商户
        walletText = QString("%1 元 (收入)").arg(walletBalance, 0, 'f', 2);
        break;
    case 3: // 骑手
        walletText = QString("%1 元 (收入)").arg(walletBalance, 0, 'f', 2);
        break;
    default:
        walletText = "0.00 元";
        break;
    }
    walletLabel->setText(walletText);
}

void ProfilePage::onNameEditToggled(bool checked)
{
    nameEdit->setReadOnly(!checked);
    saveNameButton->setEnabled(checked);

    if (checked) {
        nameEdit->setFocus();
        nameEdit->setCursorPosition(nameEdit->text().length());
    }
}

void ProfilePage::onAddressEditToggled(bool checked)
{
    addressEdit->setReadOnly(!checked);
    saveAddressButton->setEnabled(checked);

    if (checked) {
        addressEdit->setFocus();
        addressEdit->setCursorPosition(addressEdit->text().length());
    }
}

void ProfilePage::onSaveNameClicked()
{
    QString newName = nameEdit->text().trimmed();

    if (newName.isEmpty()) {
        QMessageBox::warning(this, "错误", "昵称不能为空！");
        return;
    }

    if (newName == originalName) {
        nameEditCheckBox->setChecked(false);  // 没有变化，直接关闭编辑模式
        return;
    }

    // 根据用户身份确定表名和字段名
    QString tableName;
    QString nameField;

    if(userIdentity == 0){
        tableName = "admin";
        nameField = "admin_name";
    }else if(userIdentity == 1){
        tableName = "user";
        nameField = "user_name";
    }else if(userIdentity == 2){
        tableName = "business";
        nameField = "business_name";
    }else if(userIdentity == 3){
        tableName = "rider";
        nameField = "rider_name";
    }else{
        QMessageBox::warning(this, "错误", "未知用户身份！");
        return;
    }

    // 更新数据库
    QString sql = QString("UPDATE %1 SET %2 = '%3' WHERE phone_id = %4")
                 .arg(tableName).arg(nameField).arg(newName).arg(phoneId);

    QSqlQuery query = db.exec(sql);

    if (query.isActive()) {
        QMessageBox::information(this, "成功", "昵称已更新！");
        originalName = newName;
        nameEditCheckBox->setChecked(false);  // 关闭编辑模式

        // 发送信号通知昵称已更改
        emit nameChanged(newName);
    } else {
        QMessageBox::warning(this, "错误", "更新昵称失败！");
    }
}

void ProfilePage::onSaveAddressClicked()
{
    QString newAddress = addressEdit->text().trimmed();

    if (newAddress.isEmpty()) {
        QMessageBox::warning(this, "错误", "地址不能为空！");
        return;
    }

    if (newAddress == originalAddress) {
        addressEditCheckBox->setChecked(false);  // 没有变化，直接关闭编辑模式
        return;
    }

    // 更新地址表
    QString sql;
    if(address == NULL){
        sql = QString("insert into address(user_id,address,address_status) values(%1,'%2',1)")
                     .arg(userId).arg(newAddress);
    }else{
        sql = QString("UPDATE address SET address = '%1' WHERE user_id = %2")
                     .arg(newAddress).arg(userId);
    }
    qDebug()<<"profilePage-320:"<<sql;
    QSqlQuery query = db.exec(sql);

    if (query.isActive()) {
        QMessageBox::information(this, "成功", "地址已更新！");
        originalAddress = newAddress;
        addressEditCheckBox->setChecked(false);  // 关闭编辑模式

        // 发送信号通知地址已更改
        emit addressChanged(newAddress);
    } else {
        QMessageBox::warning(this, "错误", "更新地址失败！");
    }
}

void ProfilePage::onChangePasswordClicked()
{
    showPasswordChangeDialog();
}

bool ProfilePage::showPasswordChangeDialog()
{
    bool success = false;
    
    // 创建密码修改对话框
    QDialog passwordDialog(this);
    passwordDialog.setWindowTitle("修改密码");
    passwordDialog.setFixedSize(350, 250);
    passwordDialog.setWindowFlags(Qt::Dialog | Qt::WindowTitleHint | Qt::CustomizeWindowHint | Qt::WindowCloseButtonHint);
    
    QVBoxLayout *layout = new QVBoxLayout(&passwordDialog);
    layout->setSpacing(15);
    layout->setContentsMargins(20, 20, 20, 20);
    
    // 标题
    QLabel *titleLabel = new QLabel("修改密码", &passwordDialog);
    titleLabel->setStyleSheet("font-size: 16pt; font-weight: bold;");
    titleLabel->setAlignment(Qt::AlignCenter);
    layout->addWidget(titleLabel);
    
    // 表单
    QFormLayout *formLayout = new QFormLayout();
    formLayout->setSpacing(10);
    
    // 当前密码
    QLineEdit *currentPasswordEdit = new QLineEdit(&passwordDialog);
    currentPasswordEdit->setEchoMode(QLineEdit::Password);
    currentPasswordEdit->setStyleSheet("font-size: 12pt; padding: 8px; border: 1px solid #ccc; border-radius: 4px;");
    formLayout->addRow(new QLabel("当前密码:", &passwordDialog), currentPasswordEdit);
    
    // 新密码
    QLineEdit *newPasswordEdit = new QLineEdit(&passwordDialog);
    newPasswordEdit->setEchoMode(QLineEdit::Password);
    newPasswordEdit->setStyleSheet("font-size: 12pt; padding: 8px; border: 1px solid #ccc; border-radius: 4px;");
    formLayout->addRow(new QLabel("新密码:", &passwordDialog), newPasswordEdit);
    
    // 确认新密码
    QLineEdit *confirmPasswordEdit = new QLineEdit(&passwordDialog);
    confirmPasswordEdit->setEchoMode(QLineEdit::Password);
    confirmPasswordEdit->setStyleSheet("font-size: 12pt; padding: 8px; border: 1px solid #ccc; border-radius: 4px;");
    formLayout->addRow(new QLabel("确认新密码:", &passwordDialog), confirmPasswordEdit);
    
    layout->addLayout(formLayout);
    
    // 按钮
    QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, &passwordDialog);
    buttonBox->button(QDialogButtonBox::Ok)->setText("确认");
    buttonBox->button(QDialogButtonBox::Cancel)->setText("取消");
    buttonBox->button(QDialogButtonBox::Ok)->setStyleSheet("font-size: 12pt; padding: 8px 16px; border-radius: 4px; background-color: #4CAF50; color: white;");
    buttonBox->button(QDialogButtonBox::Cancel)->setStyleSheet("font-size: 12pt; padding: 8px 16px; border-radius: 4px;");
    layout->addWidget(buttonBox);
    
    // 连接信号槽
    connect(buttonBox, &QDialogButtonBox::accepted, [&]() {
        QString currentPassword = currentPasswordEdit->text();
        QString newPassword = newPasswordEdit->text();
        QString confirmPassword = confirmPasswordEdit->text();
        
        // 验证输入
        if (currentPassword.isEmpty() || newPassword.isEmpty() || confirmPassword.isEmpty()) {
            QMessageBox::warning(&passwordDialog, "错误", "所有密码字段都不能为空！");
            return;
        }
        
        if (newPassword != confirmPassword) {
            QMessageBox::warning(&passwordDialog, "错误", "两次输入的新密码不一致！");
            return;
        }
        
        // 验证当前密码
        if (!verifyCurrentPassword(currentPassword)) {
            QMessageBox::warning(&passwordDialog, "错误", "当前密码不正确！");
            return;
        }
        
        // 更新密码
        if (updatePassword(newPassword)) {
            QMessageBox::information(&passwordDialog, "成功", "密码已成功修改！");
            success = true;
            passwordDialog.accept();
        } else {
            QMessageBox::warning(&passwordDialog, "错误", "密码修改失败！");
        }
    });
    
    connect(buttonBox, &QDialogButtonBox::rejected, &passwordDialog, &QDialog::reject);
    
    // 显示对话框
    passwordDialog.exec();
    
    return success;
}

bool ProfilePage::verifyCurrentPassword(const QString &currentPassword)
{
    // 构建查询语句验证当前密码
    QString sql = QString("SELECT * FROM phone WHERE phone_id = %1 AND password = '%2'")
                 .arg(phoneId).arg(currentPassword);
    
    QSqlQuery query = db.exec(sql);
    
    // 如果查询成功且存在结果，说明密码正确
    return query.isActive() && query.next();
}

bool ProfilePage::updatePassword(const QString &newPassword)
{
    // 构建更新语句
    QString sql = QString("UPDATE phone SET password = '%1' WHERE phone_id = %2")
                 .arg(newPassword).arg(phoneId);
    
    QSqlQuery query = db.exec(sql);
    
    // 如果查询成功，说明更新成功
    return query.isActive();
}

void ProfilePage::onBecomeMerchantClicked()
{
    // 创建并显示商户注册窗口
    MerchantRegisterWindow *registerWindow = new MerchantRegisterWindow(db, userId, phoneId, this);
    registerWindow->setAttribute(Qt::WA_DeleteOnClose);
    registerWindow->setWindowModality(Qt::ApplicationModal);
    registerWindow->show();
    registerWindow->activateWindow();
    registerWindow->raise();
}

void ProfilePage::onBecomeRiderClicked()
{
    // 创建并显示骑手注册窗口
    RiderRegisterWindow *registerWindow = new RiderRegisterWindow(db, userId, phoneId, this);
    registerWindow->setAttribute(Qt::WA_DeleteOnClose);
    registerWindow->setWindowModality(Qt::ApplicationModal);
    registerWindow->show();
    registerWindow->activateWindow();
    registerWindow->raise();
}

void ProfilePage::onRechargeClicked()
{
    if (userIdentity != 1) {
        return; // 只有普通用户才能充值
    }
    
    bool ok;
    double amount = QInputDialog::getDouble(this, "钱包充值", 
                                           "请输入充值金额:", 
                                           0.0, 0.01, 10000.0, 2, &ok);
    
    if (ok && amount > 0) {
        // 更新数据库
        double newBalance = walletBalance + amount;
        QString sql = QString("UPDATE user SET user_money = %1 WHERE phone_id = %2")
                     .arg(newBalance).arg(phoneId);
        
        QSqlQuery query = db.exec(sql);
        
        if (query.isActive()) {
            walletBalance = newBalance;
            updateWalletDisplay();
            QMessageBox::information(this, "充值成功", QString("成功充值 %1 元，当前余额: %2 元")
                                    .arg(amount, 0, 'f', 2)
                                    .arg(walletBalance, 0, 'f', 2));
        } else {
            QMessageBox::warning(this, "充值失败", "无法更新钱包余额，请稍后再试。");
        }
    }
}

void ProfilePage::onChangeAvatarClicked()
{
    if (userIdentity != 2) return;
    QString fileName = database::copyImageToDirectory("../img");
    if (!fileName.isEmpty()) {
        QPixmap pixmap(fileName);
        if (!pixmap.isNull()) {
            pixmap = pixmap.scaled(avatarLabel->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation);
            avatarLabel->setPixmap(pixmap);
            avatarPath = fileName;
            // 保存到数据库
            QString sql = QString("UPDATE business SET img = '%1' WHERE phone_id = %2").arg(avatarPath).arg(phoneId);
            QSqlQuery query = db.exec(sql);
            if (query.isActive()) {
                QMessageBox::information(this, "成功", "头像已更新！");
                emit profileUpdated();
            } else {
                QMessageBox::warning(this, "错误", "头像更新失败！");
            }
        } else {
            QMessageBox::warning(this, "警告", "无法加载图片文件!");
        }
    }
}

void ProfilePage::onStatusToggleClicked()
{
    if (userIdentity != 2) return;
    int newStatus = (businessStatus == 1) ? 0 : 1;
    QString sql = QString("UPDATE business SET status = %1 WHERE phone_id = %2").arg(newStatus).arg(phoneId);
    QSqlQuery query = db.exec(sql);
    if (query.isActive()) {
        businessStatus = newStatus;
        statusLabel->setText(businessStatus == 1 ? "营业中" : "休息中");
        toggleStatusButton->setText(businessStatus == 1 ? "设为休息" : "设为营业");
        QMessageBox::information(this, "成功", businessStatus == 1 ? "已设为营业" : "已设为休息");
        emit profileUpdated();
    } else {
        QMessageBox::warning(this, "错误", "营业状态更新失败！");
    }
}

bool ProfilePage::eventFilter(QObject *obj, QEvent *event)
{
    if (obj == avatarLabel && event->type() == QEvent::MouseButtonRelease) {
        onChangeAvatarClicked();
        return true;
    }
    return QWidget::eventFilter(obj, event);
}
